package netip

import (
	"fmt"
	"net"
	"regexp"

	"strconv"
	"strings"
	//"syscall"
	//"unsafe"
)

//IPCfg ip配置
type IPCfg struct {
	Name    string
	IP      string
	NetMask string
	Gateway string
	Mac     string
	//InterfaceName string
}
type RtInfo struct {
	Dst              net.IPNet
	Gateway, PrefSrc net.IP
	OutputIface      uint32
	Priority         uint32
}

type RouteSlice []*RtInfo

type Router struct {
	Ifaces []net.Interface
	Addrs  []net.IP
	V4     RouteSlice
}

func parseMask(mask byte) string {
	var value uint32
	value = 1<<32 - 1
	var result string
	value = value << (32 - int(mask))
	for i := 0; i < 4; i++ {
		cv := (value >> (i * 8) & 255)
		if i == 0 {
			result = fmt.Sprintf("%d", cv) + result
		} else {
			result = fmt.Sprintf("%d.", cv) + result
		}
	}
	return result
}

//GetIPs 获取网络ip地址
func GetIPs() ([]IPCfg, error) {
	ifs, _ := net.Interfaces()
	ipcfgs := make([]IPCfg, 0)
	rs := "((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}"
	reg := regexp.MustCompile(rs)
	for _, ipf := range ifs {

		addrs, _ := ipf.Addrs()
		for _, addr := range addrs {
			saddr := addr.String()
			ipParts := strings.Split(saddr, "/")
			if len(ipParts) == 2 {
				if reg.MatchString(ipParts[0]) {
					nmask, err := strconv.Atoi(ipParts[1])
					if err == nil && nmask > 1 && nmask < 31 {
						var ipcfg IPCfg
						ipcfg.NetMask = parseMask(byte(nmask))
						ipcfg.Name = ipf.Name
						ipcfg.Mac = ipf.HardwareAddr.String()
						ipcfg.IP = ipParts[0]
						ipcfgs = append(ipcfgs, ipcfg)
						fmt.Println("--------------********", ipcfg)
					}

				}
			}
		}

	}
	newRoute, rerr := GetRouteInfo()
	if rerr == nil && newRoute != nil {
		for _, rt := range newRoute.V4 {
			if rt.Gateway != nil {
				//fmt.Printf("%-15v %-15v %-15v\n", newRoute.ifaces[rt.OutputIface-1].Name, rt.Gateway.String(), newRoute.addrs[rt.OutputIface-1])
				for i := range ipcfgs {
					if ipcfgs[i].Name == newRoute.Ifaces[rt.OutputIface-1].Name {
						ipcfgs[i].Gateway = rt.Gateway.String()
						break
					}
				}
			}
		}

	}
	return ipcfgs, nil
}
